package linkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description: 19.删除链表倒数第N个结点
 * User: Li_yizYa
 * Date: 2025—03—24
 * Time: 23:55
 */
public class Solution4 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = null;
        ListNode ret = removeNthFromEnd(node1, 2);
        while (ret != null) {
            System.out.print(ret.val + " ");
            ret = ret.next;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (n > 0 && fast != null && fast.next != null) {
            fast = fast.next;
            n--;
        }
        if (n == 1) {
            return head.next;
        }

        while (fast != null && fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
